package com.fusionride.wellness.service.consumer;

import com.alibaba.fastjson.JSONObject;
import com.fusionride.wellness.service.impl.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

/**
 * 处理mqtt的具体消息
 */
@Slf4j
@Component
public class MqttMsgConsumer implements MessageHandler {
    @Autowired
    private WebSocketService webSocketService;

    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        String str = message.getPayload().toString();
//        log.info("mqtt消费 " + message.getHeaders().get("mqtt_receivedTopic") + " " + msg);

        if (str.substring(24, 26).equals("01")){
            JSONObject jo = new JSONObject();
            String timeStampHex = str.substring(5, 16);
            String SNHex = str.substring(16,24);
            String msgFrameHex = str.substring(24,26);
            String protocolVersionHex = str.substring(26,28);
            String BreathRateHex = str.substring(28,36);
            String heartRateHex = str.substring(36,44);
            long timeStamp = Long.parseLong(timeStampHex, 16);
            Integer msgFrame = Integer.valueOf(msgFrameHex, 16);
            Integer protocolVersion = Integer.valueOf(protocolVersionHex, 16);
            BigInteger BreathRateBI = new BigInteger(BreathRateHex,16);
            float BreathRate = Float.intBitsToFloat(BreathRateBI.intValue());
            BigInteger heartRateBI = new BigInteger(heartRateHex,16);
            float heartRate = Float.intBitsToFloat(heartRateBI.intValue());
            jo.put("timeStamp",timeStamp);
            jo.put("SN",SNHex);
            jo.put("msgFrame",msgFrame);
            jo.put("protocolVersion",protocolVersion);
            jo.put("breathing",BreathRate);
            jo.put("heart",heartRate);
            log.info("mqtt消费 " + message.getHeaders().get("mqtt_receivedTopic") + " " + jo);
            // 发送消息
            this.webSocketService.sendMessage(jo.toString());
        }

    }
}
